﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Thor.Common;

namespace Thor.Repository.Azure.Queue
{
    public class MessageRepository : QueueRepositoryBase, IMessageRepository
    {
        #region Constructors

        public MessageRepository(Dictionary<string, object> repositoryParameters)
            : base(repositoryParameters) { }

        #endregion

        #region IMessageRepository Members

        public void Insert(Message message)
        {
            GetQueue().AddMessage(new CloudQueueMessage(Encoding.UTF8.GetBytes(message.Text)));
        }

        public Message Fetch()
        {
            var queueMsg = GetQueue().GetMessage();

            if (queueMsg != null)
                return new Message() { Id = queueMsg.Id, Text = queueMsg.AsString };
            else
                return null;
        }

        public Message Peek()
        {
            var queueMsg = GetQueue().PeekMessage();

            if (queueMsg != null)
                return new Message() { Id = queueMsg.Id, Text = queueMsg.AsString };
            else
                return null;
        }

        public void Delete(Message message)
        {
            int msgCount = GetQueue().RetrieveApproximateMessageCount();
            var queueMsg = GetQueue().GetMessages(msgCount).Where(m => m.Id == message.Id).FirstOrDefault();

            if (queueMsg != null)
                GetQueue().DeleteMessage(queueMsg);
        }

        public void Clear()
        {
            GetQueue().Clear();
        }

        #endregion
    }
}
